import { defineStore } from 'pinia';
import { ROLE_TYPE } from '@/config/app';

export const useUserStore = defineStore("user", {
  state: () => ({
    tabbar: [],
    role: "user", // 'user' 或 'merchant'
    accessToken: "",
    tabIndex: 0,
  }),
  actions: {
    setRole(newRole) {
      this.role = newRole;
      // 移除存储到localStorage的代码
      // 角色改变时，获取对应角色的tabbar数据
      this.fetchTabbarData();
    },
    setToken(accessToken) {
      this.accessToken = accessToken || "";

      // 存储到本地
      if (accessToken) {
        uni.setStorageSync("accessToken", accessToken);
      } else {
        uni.removeStorageSync("accessToken");
      }
    },
    // 其他方法保持不变
    setTabbar(newTabbar) {
      this.tabbar = newTabbar;
    },
    setTabIndex(index) {
      this.tabIndex = index;
    },
    // 获取tabbar数据
    async fetchTabbarData() {
      try {
        let tabbarData = [];

        // 根据角色获取tabbar数据
        if (this.role === ROLE_TYPE.MERCHANT) {
          tabbarData = [
            {
              pagePath: "/pages/merchant/index/index",
              text: "商家首页",
            },
            {
              pagePath: "/pages/merchant/category/index",
              text: "商品管理",
            },
            {
              pagePath: "/pages/merchant/dynamics/index",
              text: "商家动态",
            },
            {
              pagePath: "/pages/merchant/mine/index",
              text: "商家中心",
            },
          ];
        } else {
          tabbarData = [
            {
              pagePath: "/pages/customer/index/index",
              text: "首页",
            },
            {
              pagePath: "/pages/customer/category/index",
              text: "分类",
            },
            {
              pagePath: "/pages/customer/dynamics/index",
              text: "行程",
            },
            {
              pagePath: "/pages/customer/mine/index",
              text: "我的",
            },
          ];
        }

        // 设置tabbar数据
        this.setTabbar(tabbarData);
        console.log("Tabbar数据已更新:", this.tabbar);

        // 通知tabbar组件更新
        uni.$emit("tabbarUpdate");
      } catch (error) {
        console.error("获取tabbar数据失败:", error);
      }
    },
    // 更新原生tabBar
    updateNativeTabBar() {
      try {
        // 获取当前tabbar数据
        const currentTabbar = this.tabbar || [];

        // 清空现有的tabBar
        uni.hideTabBar();

        // 只处理前5个tabBar项
        const tabBarItems = currentTabbar.slice(0, 5);

        // 动态设置tabBar
        if (tabBarItems.length > 0) {
          // 显示tabBar
          uni.showTabBar({
            animation: true,
          });
        }
      } catch (error) {
        console.error("更新原生tabBar失败:", error);
      }
    },
  },
});